import React, { Component } from 'react';
import { Grid, Tag, Loading, Notice, Balloon } from '@icedesign/base';
import IceContainer from '@icedesign/container';
import DataBinder from '@icedesign/data-binder';
import { getRDchart, getKeyWorkCloudChart, getLeftDarChart, getMapChart, getFXPiachart } from '../../../../echarts-figures.js';

import './UserTrafficStastistics.scss';

var echarts = require('echarts');
import 'echarts/map/js/china.js';
import 'echarts-wordcloud';
import { GetUrlParam } from '../../../../baseConfig.js';

const { Row, Col } = Grid;
const Tooltip = Balloon.Tooltip;
// const onClose = () => console.log("onClose triggered!");
// const afterClose = () => console.log("afterClose triggered!");

@DataBinder({
  LineChartData: {
    // url: 'api/getTraditionalScoreChart',
    url: `${global.constants.GOLDEYEGETHOST}cattle/opinion_info_trend`,
    type: 'get',
    responseFormatter: (responseHandler, res, originResponse) => {
      // console.log("responseHandler",responseHandler)
      // // 做一些数据转换
      // const newRes = {
      //   status: res.code !== 0 ? 'SUCCESS' : 'ERROR',
      //   message: res.successMsg,
      // };
      // // 回传给处理函数
      // // 不做回传处理会导致数据更新逻辑中断
      // responseHandler(newRes, originResponse);
    },
  },

  KeyWordChartData: {
    // url: './mock/getKeywordCloud.json',
    url:`${global.constants.GOLDEYEGETHOST}cattle/opinion_word_cloud`,
    type: 'get',
  },

  LeftDarChartData: {
    // url: './mock/getLeftBarData.json',
    url:`${global.constants.GOLDEYEGETHOST}cattle/opinion_media_rate`,
    type: 'get',
  },

  getMapChartData: {
    // url: './mock/getMapChartData.json',
    url:`${global.constants.GOLDEYEGETHOST}cattle/opinion_area_info`,
    type: 'get',
  },

  getGaugeChartData: {
    url: `${global.constants.GOLDEYEGETHOST}cattle/opinion_emotion_info`,
    type: 'get',
  },

  getHighwordChartData: {
    url: `${global.constants.GOLDEYEGETHOST}cattle/opinion_positive_word`,
    type: 'get',
  },

  getNegativehwordChartData: {
    url: `${global.constants.GOLDEYEGETHOST}cattle/opinion_negative_word`,
    type: 'get',
  }
})

export default class UserTrafficStastistics extends Component {
  static displayName = 'UserTrafficStastistics';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {

      visible:false,

      machineCode:'',
      error:false,

      LineChartID:'LineChartBox',
      messageLoading:true,
      numbers:{},
      
      KeywordCloudChartID:'KeyWordChartBox',
      keywordLoading:true,
      KeywordConfig:{},

      LeftDarChartID:'LeftDarchartBox',
      mediaLoading:true,
      DarChartConfig:{},

      MapChartID:'MapChartBox',
      mapLoading:true,
      MapData:[],
      MapConfig:{},

      GaugeChartID:'GaugeChartBox',
      GaugeLoading:true,
      GaugeConfig:{},

      Highword:[],
      lowword:[],
    };
  }

  componentWillMount(){

  }

  componentDidMount() {
    //折线图数据处理
    this.props.updateBindingData('LineChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      // console.log("获取折线数据",data);
      if(data.flag){
        this.setState({
          messageLoading:false,
          numbers:getRDchart(
            '信息属性走势图',
            data.data.data_info.dates,
            data.data.data_info.data,
          )
        })
        this.initChart(this.state.numbers,this.state.LineChartID);
      }else{
        console.log("暂无数据")
      }
    });

    // 关键词云数据处理
    this.props.updateBindingData('KeyWordChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      console.log("关键词云",data);
      if(data.flag){
        this.setState({
          keywordLoading:false,
          KeywordConfig:getKeyWorkCloudChart(
            '关键词云',
            // keywordcloud,
            data.data.data_info,
          ) 
        })
        this.initKeywordChart(this.state.KeywordConfig,this.state.KeywordCloudChartID);
      }else{
        console.log("关键词云暂无数据")
      }
    });

    //媒体来源占比图
    this.props.updateBindingData('LeftDarChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      // console.log("data",data.data.data_list);
      if(data.flag){
        let xdata = [];
        let ydata = [];
        
        for(let i=0; i<data.data.data_list.length; i++){
          xdata.push(data.data.data_list[i].sources);
          ydata.push(data.data.data_list[i].value);
        }

        this.setState({
          mediaLoading:false,
          DarChartConfig:getLeftDarChart(
            xdata,
            ydata
          ) 
        })
        // console.log("媒体来源占比图",this.state.DarChartConfig);
        this.initChart(this.state.DarChartConfig,this.state.LeftDarChartID);
      }else{
        console.log("媒体来源占比图暂无数据")
      }
    });

    //地域分析
    this.props.updateBindingData('getMapChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      // console.log("MapData",data.data.data_list);
      if(data.flag){
        this.setState({
          mapLoading:false,
          MapData:data.data.data_list,
          MapConfig:getMapChart(
            '情感分布图',
            data.data.data_list,
          ) 
        })
        // console.log("地域分析",this.state.MapConfig);
        this.initMapChart(this.state.MapConfig,this.state.MapChartID);
      }else{
        console.log("地域分析暂无数据")
      }
    });

    //情感分布
    this.props.updateBindingData('getGaugeChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      // console.log("情感分布饼状图数据",data);
      if(data.flag){
        this.setState({
          GaugeLoading:false,
          GaugeConfig:getFXPiachart(
            '情感分布图',
            data.data.data_list,
          ),
        })
        // console.log("地域分析",this.state.GaugeConfig);
        this.initGaugeChart(this.state.GaugeConfig,this.state.GaugeChartID);
      }else{
        console.log("情感分布暂无数据")
      }
    });

    //高频词汇
    this.props.updateBindingData('getHighwordChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      // console.log("Highword",data)
      if(data.flag){
        let cc = []
        for(let i=0;i<data.data.data_info.length;i++){
          cc.push(data.data.data_info[i]);
        }
        this.setState({
          Highword:cc,
        })
      }else{
        console.log("暂无正面词汇")
      }
      
    });

    this.props.updateBindingData('getNegativehwordChartData',{
      'params': {
        secu_code:GetUrlParam("secu_code")
      }
    }, (data) => {
      // console.log("Low",data)
      if(data.flag){
        this.setState({
          lowword:data.data.data_info,
        })
      }else{
        console.log("暂无负面词汇")
      }
    });

  }

  //信息走势图Title
  renderMessageTitle = () => {
    return(
      <span>信息走势图</span>
    )
  }

  //公共图表
  initChart(config,id,a) {
    let myChart = echarts.getInstanceByDom(document.getElementById(id));
    if( myChart === undefined){
        myChart = echarts.init(document.getElementById(id));
    }
    if(a){
      myChart.setOption(config,true);
    }else{
      myChart.setOption(config);
    }
    window.addEventListener('resize',()=>{
      myChart.resize();
    });
  }

  //关键词云
  initKeywordChart(config,id) {
    // console.log(config);
    let keywordChart = echarts.getInstanceByDom(document.getElementById(id));
    if( keywordChart === undefined){
      keywordChart = echarts.init(document.getElementById(id));
    }

    keywordChart.setOption(config);

    keywordChart.on('click', function(params) {
        // alert('搜索关键词' + (params.name));
        // window.open('https://www.baidu.com/s?wd=' + encodeURIComponent(params.name));
    });
    
    window.addEventListener('resize',()=>{
      keywordChart.resize();
    });
  }

  //地图
  initMapChart(config,id) {
    // console.log(config);
    let mapChart = echarts.getInstanceByDom(document.getElementById(id));
    if( mapChart === undefined){
      mapChart = echarts.init(document.getElementById(id));
    }

    mapChart.setOption(config);

    window.addEventListener('resize',()=>{
      mapChart.resize();
    });
  }

  //敏感分布图
  initGaugeChart(config,id) {
    // console.log(config);
    let GaugeChart = echarts.getInstanceByDom(document.getElementById(id));
    if( GaugeChart === undefined){
      GaugeChart = echarts.init(document.getElementById(id));
    }

    GaugeChart.setOption(config);

    window.addEventListener('resize',()=>{
      GaugeChart.resize();
    });
  }

// 　GetUrlParam(paraName) {
// 　　var url = document.location.toString();
// 　　var arrObj = url.split("?");
// 　　　　if (arrObj.length > 1) {
// 　　　　　　var arrPara = arrObj[1].split("&");
// 　　　　　　var arr;
// 　　　　　　for (var i = 0; i < arrPara.length; i++) {
// 　　　　　　　　arr = arrPara[i].split("=");
// 　　　　　　　　if (arr != null && arr[0] == paraName) {
// 　　　　　　　　　　return arr[1];
// 　　　　　　　　}
// 　　　　　　}
// 　　　　　　return "";
// 　　　　}
// 　　　　else {
// 　　　　　　return "";
// 　　　　}
// 　　}

  renderTrafficTypes = () => {
    return (
      <div>
        <IceContainer className="ContainerRadius">
          <div className="title"><div className="kk"></div>信息走势图</div>
          <div className="left-chart-box">
            <div id={this.state.LineChartID} style={{width: "100%", Width:'480px', height: "400px", padding:'0 20px'}}><Loading shape="fusion-reactor" visible={this.state.messageLoading} color="#fff"></Loading></div>
          </div>
        </IceContainer>

        <IceContainer className="ContainerRadius">
          <div className="title"><div className="kk"></div>关键词云</div>
          <div className="left-chart-box">
            <div id={this.state.KeywordCloudChartID} style={{width: "100%", Width:'480px', height: "400px", padding:'0 20px'}}><Loading shape="fusion-reactor" visible={this.state.keywordLoading} color="#fff"></Loading></div>
          </div>
        </IceContainer>

        <IceContainer className="ContainerRadius">
          <div className="title"><div className="kk"></div>地域分析</div>
          {/* <div style={styles.inlineFlex}> */}
            <div>
              <div id={this.state.MapChartID} style={{width: "400px", height: "386px",float:'left', padding:'0 20px'}}><Loading shape="fusion-reactor" visible={this.state.mapLoading} color="#fff"></Loading></div>
            </div>
            {/* <Row className="map-table"> */}
            <div className="map-table">
              {this.state.MapData.map((item,i) => {
                return(
                  // <Col key={i} span="1p5">
                    // {item.name}({item.value})
                    <div key={i} className="card-box">{item.name}({item.value})</div>
                  // </Col>
                )
              })}
            </div>
          {/* </div> */}
          {/* </Row> */}
        </IceContainer>
      </div>
    );
  };

  handleVisibleChange(visible) {
    this.setState({ visible });
  }


  // renderUserStatistics = () => {
  //   return (
  //     <IceContainer title="地域分析">
  //       <div className="map-chart-box">
  //         <div id={this.state.MapChartID} style={{width: "100%", height: "100%"}}></div>
  //       </div>
  //     </IceContainer>
  //   );
  // };

  // visibleTrigger = (item,i) =>{
  //   return(
  //     <Tag shape="readonly" key={i} className="negative-font">{item}</Tag>
  //   )
  // }
  topShow = (item,i) => {
    return(
      <Tag shape="readonly" className="negative-font">{item}</Tag>
    )
  }

  renderBrowserStatus = (item,i) => {
    return (
      <div>
        {/* <Loading shape="fusion-reactor" visible={this.state.GaugeLoading} color="#fff"> */}
          <IceContainer className="ContainerRadius">
            <div className="title"><div className="kk"></div>情感分布图</div>
            <div className="left-chart-box">
              <div id={this.state.GaugeChartID} style={{width: "100%", width:'480px', height: "400px", padding:'0 20px'}}><Loading shape="fusion-reactor" visible={this.state.GaugeLoading} color="#fff"></Loading></div>
            </div>
          </IceContainer>
        {/* </Loading> */}

        <IceContainer className="ContainerRadius">
          <div className="title"><div className="kk"></div>媒体来源占比图</div>
          <div className="left-chart-box">
            <div id={this.state.LeftDarChartID} style={{width: "100%", width:'480px', height: "400px"}}><Loading shape="fusion-reactor" visible={this.state.mediaLoading} color="#fff"></Loading></div>
          </div>
        </IceContainer>
        <IceContainer className="ContainerRadius">
        <div className="title"><div className="kk"></div>高频词汇</div>
        <div style={{minHeight:'386px'}}>
          <Row wrap gutter="20">
            <Col xxs="24" l="12" className="zfbox">
              <div className="gpt"><img src="./assetc/zhengmian.png" /><p style={{fontWeight:'bold'}}>正面</p></div>
              { this.state.Highword.map((item,i) => {
                return(
                  <div style={{float:'left'}} key={item}>
                    <Tooltip trigger={this.topShow(item,i)} align="t" text={item}>{item}</Tooltip>
                  </div>
                  // <Tag shape="readonly" key={i} className="positive-font">{item}</Tag>
                )
              })}
            </Col>
            <Col xxs="24" l="12" className="zfbox">
              <div className="gpt"><img src="./assetc/fumian.png" /><p style={{fontWeight:'bold'}}>负面</p></div>
              <div style={{display:'block',width:'100%'}}>
              { this.state.lowword.map((item,i) => {
                return(
                  <div style={{float:'left'}} key={item}>
                    <Tooltip trigger={this.topShow(item,i)} align="t" text={item} className="tooltip-shadow" style={{backgroundColor:'#fff',border:'1px solid #f1f1f1'}}>{item}</Tooltip>
                  </div>
                )
              })}
              </div>
            </Col>
          </Row>
        </div>
        </IceContainer>
      </div>
    );
  };

  render() {

    return (
      <div className="user-traffic-stastistics">
        {/* <Notice title="title" visible={this.state.error} closable onClose={onClose} afterClose={afterClose}>
          暂时没有获取到数据，请检查您的网络，或者联系管理员查看原因。
        </Notice> */}
        <Row wrap gutter="20">
          <Col xxs="24" l="12">
            {this.renderTrafficTypes()}
          </Col>
          {/* <Col xxs="24" l="12">
            {this.renderUserStatistics()}
          </Col> */}
          <Col xxs="24" l="12">
            {this.renderBrowserStatus()}
          </Col>
        </Row>
      </div>
    );
  }
}

const styles = {
  browserItem: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: '5px 0',
    // borderBottom: '1px dotted #eee',
  },
  percentage: {
    padding: '2px 5px',
    backgroundColor: '#307bf0',
    color: '#fff',
    borderRadius: '14px',
    fontSize: '12px',
  },
  satisfaction: {
    textAlign: 'center',
    fontSize: '36px',
    color: '#307bf0',
    padding: '0 0 8px',
  },
  satisfactionItem: {
    textAlign: 'center',
    fontWeight: 500,
  },
  subtitle: {
    fontSize: '13px',
    color: '#999',
    marginBottom: '5px',
    fontWeight: 400,
  },
  inlineFlex:{
    display:'inline-flex'
  }
};


                  //   <Balloon
                  //     trigger={top}
                  //     align="t"
                  //     alignment="edge"
                  //     triggerType="hover"
                  //     style={{ width: 300 }}
                  //     key={`${item}-${i}`}
                  //   >{item}</Balloon>
                  //   <Tag shape="readonly" key={i} className="negative-font">{item}</Tag>
                  // </div>